/**
 * @author sunfengjia edit
 * 说明：         使用json数据格式，生成N级下拉框
 * params:
 * data:          json对象
 * select:      级联下拉框名称

 调用eg：
 var comboselect = ComboSelectFactory(data, 'p1', 'p2', 'p3', 'p4');


 idKey: 数据的id字段名,根据这个字段进行关联,生成option的selfid属性
 valueKey: option的value属性，存库用
 textKey: 数据的显示文本字段名
 parentIdKey: 数据的父节点字段名
 topParentValue:最顶层的值
 设定下拉列表 idKey,textKey,parentIdKey,topParent名称的方法eg:
 comboselect.setProperties({idKey:'id',textKey:'text',parentIdKey:'parentid',topParentValue:'-1'});

 初始化下拉列表集合的方法eg:
 comboselect.initSelect('gd');
 */


var topParentValue = "-";
var idKey = "selfid", valueKey = "value", textKey = "text", parentIdKey = "parentid";


var ComboSelectFactory = function(data){
    return new ComboSelect(arguments);
}

var ComboSelect = function(data){
    this.myData = [].slice.call(data, 0, 1)[0];
    this.ids     = [].slice.call(data, 1);
    if(typeof this.ids[0] == "object"){this.ids = this.ids[0];}
    // this.setProperties({});
}

ComboSelect.prototype.getValue = function(index){
    var value = "";
    if(typeof index != "undefined"){
        return this.$(this.ids[index]).value;
    }
    for(var len = this.ids.length,i = len; i>0; i--){
        if(this.$(this.ids[i-1]).value && this.$(this.ids[i-1]).value != ""){
            value = this.$(this.ids[i-1]).value;
            break;
        }
    }
    return value;
}


ComboSelect.prototype.getText = function(index){
    var text = "";
    if(typeof index != "undefined"){
        return $(this.$(this.ids[index])).find(":selected").text();
    }
    for(var len = this.ids.length,i = len; i>0; i--){
        if(this.$(this.ids[i-1]).value && this.$(this.ids[i-1]).value != ""){
            text = $(this.$(this.ids[i-1])).find(":selected").text();
            break;
        }
    }
    return text;
}

ComboSelect.prototype.getValueIndex = function(){
    var i = "";
    for(var len = this.ids.length,i = len; i>0; i--){
        if(this.$(this.ids[i-1]).value && this.$(this.ids[i-1]).value != ""){
            return i;
        }
    }
}

ComboSelect.prototype.setProperties = function(opt){
    this.topParentValue  = opt.topParentValue || topParentValue;
    this.idKey           = opt.idKey || idKey;
    this.valueKey        = opt.valueKey || this.idKey;
    this.textKey         = opt.textKey || textKey;
    this.parentIdKey     = opt.parentIdKey || parentIdKey;

    for(var i=0, len=this.ids.length; i<len; i++){
        var o = this.$(this.ids[i]);
        //给第i个select添加change事件，初始化该下拉列表的下级select
        this.addEventHandler(o, 'change', this.eventHandle(o,i));
    }

    this.initChild(null, 0);
}

ComboSelect.prototype.eventHandle = function(o,i) {
    var self     = this;
    var oreg     = o;
    var index    = i+1;
    return function() {
        self.initChild(oreg, index);
        if (self.callbackFun) {
            self.callbackFun();
        }
    }
}


/**
 * 说明：              当select选定一个option后，根据该option的值，查找 parentID 为该 optionID 的项，
 *                    生成option，插入下级select。
 * @params:
 *         oSelect:     父级select对象
 *         index:       父级select索引
 */
ComboSelect.prototype.initChild = function(oSelect, index){
    var p = null == oSelect ? this.topParentValue : oSelect.options[oSelect.selectedIndex].getAttribute(this.idKey);
    var ds = this.getChilds(p);
    this.clearSelect(index);
    var child = this.$(this.ids[index]);
    for(var i=0, len=ds.length; i<len; i++){

        var currentObj = ds[i];
        var option = new Option(currentObj[this.textKey], currentObj[this.valueKey]);
        option.setAttribute(this.idKey, currentObj[this.idKey]);
        child.options[child.length] = option;

        // var currentObj = ds[i];
        // var op = document.createElement("option");
        // op.setAttribute("value", currentObj[this.valueKey]);
        // op.setAttribute(this.idKey, currentObj[this.idKey]);
        // op.appendChild(document.createTextNode(currentObj[this.textKey]));
        // child.appendChild(op);
    }

}

/**
 * 说明：              查找指定ID的子
 * @params:
 *        parentID:     查找该ID的子
 *        returns:    子的array
 */
ComboSelect.prototype.getChilds = function(parentID) {
    var childs = [];
    for(var i=0, len=this.myData.length; i<len; i++){
        if(parentID == this.myData[i][this.parentIdKey]){
            childs.push(this.myData[i]);
        }
    }
    return childs;
}

/**
 * 说明：              将索引以下的select清空
 * @params:
 *         index:      父级对象索引
 */
ComboSelect.prototype.clearSelect = function(index) {
    for(var i=index, len=this.ids.length; i<len; i++){
        this.$(this.ids[i]).length = 1;
    }
}

/**
 * 说明：              初始化下拉列表集合。
 * @params:
 *         id:         选中项ID
 */
ComboSelect.prototype.setDefaultValue = function(value){
    var parentids = [];
    var id=null;

    for(var i=0, len=this.myData.length; i<len; i++) {
        if (value == this.myData[i][this.valueKey]) {
            id = this.myData[i][this.idKey];
            break;
        }
    }
    parentids = this.getParent(id);
    for (var i=0, len=this.ids.length; i<len; i++){
        //顶层直接初始化，子级select用父级的选中值初始化
        if(i==0){
            this.initChild(null, 0);
        }else{
            this.initChild(this.$(this.ids[i-1]),i);
        }
        if(parentids[i]!=null){
            this.$(this.ids[i]).value = parentids[i][this.valueKey];
        }
    }
}
ComboSelectFactory = function(data){
    return new ComboSelect(arguments);
}

ComboSelect.prototype.setDefaultValueByArr = function(){
    var defaultValueArr = [].slice.call(arguments, 0);
    for (var i = 0; i < defaultValueArr.length; i++) {
        if(i==0){
            this.initChild(null, 0);
        }else{
            this.initChild(this.$(this.ids[i-1]),i);
        }
        this.$(this.ids[i]).value = defaultValueArr[i];
    }
}

/**
 * 说明：              得到指定ID的父级array
 * @params:
 *         id:         选中项ID
 */
ComboSelect.prototype.getParent = function(id) {
    var parents = [];
    for(var i=0, len=this.myData.length; i<len; i++){
        if(id == this.myData[i][this.idKey]){
            if(this.myData[i][this.parentIdKey] == this.topParentValue){
                parents.push(this.myData[i]);
                break;
            }else{
                parents = this.getParent(this.myData[i][this.parentIdKey]);
                parents.push(this.myData[i]);
            }
        }
    }
    return parents;
}

ComboSelect.prototype.$ = function(sid) {
    return document.getElementById(sid);
}

ComboSelect.prototype.addEventHandler = function(oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    } else if (oTarget.attachEvent) {
        oTarget.attachEvent("on" + sEventType, fnHandler);
    } else {
        oTarget["on" + sEventType] = fnHandler;
    }
}
